<template>
  <div class="main_box">
    <el-row>
      <el-col :span="12">
        <Crumbs></Crumbs>
      </el-col>
      <!--<el-col :span="12">
        <div class="opration_wrap" >

        </div>
      </el-col>-->
    </el-row>
    <el-row>
      <div class="search_wrap">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item prop="customerCode">
            <el-input v-model="searchForm.customerCode" :clearable="true" placeholder="客户编号"></el-input>
          </el-form-item>
          <el-form-item prop="customerNickName">
            <el-input v-model="searchForm.customerNickName" :clearable="true" placeholder="客户昵称"></el-input>
          </el-form-item>
          <el-form-item prop="customerName">
            <el-input v-model="searchForm.customerName" :clearable="true" placeholder="客户姓名"></el-input>
          </el-form-item>
          <el-form-item prop="tel">
            <el-input v-model="searchForm.tel" :clearable="true" placeholder="手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="provinceCityValues">
            <ProvinceCity :isChangeOnSelect="true" @provinceCityChange="handleItemChange" :provinceCityValues="searchForm.provinceCityValues"></ProvinceCity>
          </el-form-item>
          <el-form-item prop="state">
            <el-select v-model="searchForm.state" :clearable="true" placeholder="请选择状态">
              <el-option key="1" label="启用" value="1"></el-option>
              <el-option key="0" label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="date">
            <el-date-picker
              v-model="searchForm.date"
              :clearable="true"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="imageUrl" label="头像" width="50">
          <template solt-scope="scope">
            <img :src="scope.row.imageUrl" alt="img" class="photo" />
          </template>
        </el-table-column>
        <el-table-column prop="customerCode" label="客户编码" width="100" align="center"></el-table-column>
        <el-table-column prop="customerNickName" show-overflow-tooltip label="客户昵称" width="150"></el-table-column>
        <el-table-column prop="customerName" show-overflow-tooltip label="客户姓名" width="100"></el-table-column>
        <el-table-column prop="cardId" label="客户身份证号" width="150" align="center"></el-table-column>
        <el-table-column prop="tel" label="手机号码" width="120" align="center"></el-table-column>
        <el-table-column prop="sex" label="性别" :formatter="formatSex" align="center"></el-table-column>
        <el-table-column label="所在地区" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.chooseProvinceName }}</span> <span>{{ scope.row.chooseCityName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="注册时间" width="150" align="center"></el-table-column>
        <el-table-column prop="state" label="状态" :formatter="formatStatue" align="center"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-button @click="goChat(scope.row)" size="mini" style="margin-right: 10px !important">私聊</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionCustomerTel" @click.native="handleClickGetCustomerTel(scope.row)">查看联系人</el-dropdown-item>
                  <!-- 暂停使用 20190902 by lk
                  <el-dropdown-item v-has="permissionCustomerDataCall" >查看通话详情</el-dropdown-item>
                  <el-dropdown-item v-has="permissionCustomerDataSms" >查看短信记录</el-dropdown-item>
                  -->
                  <el-dropdown-item v-has="permissionResetPwd" @click.native="handleClickResetPass(scope.row)">重置密码</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleClickDisable(scope.row)">{{ scope.row.state == 0 ? '启用' : '禁用' }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>
<script>
import Crumbs from '@/components/Crumbs';
import * as validators from '@/utils/validators';
import * as message from '@/constants/message';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import ProvinceCity from '@/components/ProvinceCity';
export default {
  data() {
    return {
      searchForm: {
        customerCode: '',
        customerNickName: '',
        customerName: '',
        tel: '',
        sex: '',
        state: '',
        date: [],
        provinceCityValues: [],
      },
      permissionCheck: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_SEE',
      permissionUpStatus: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_STATE',
      permissionResetPwd: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_RESET',
      permissionCustomerTel: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_TEL',
      permissionCustomerDataCall: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_DATA_CALL',
      permissionCustomerDataSms: 'SYSTEM_MANAGER_USER_CUSTOMER_LIST_DATA_SMS',

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
        currentPage: 1,
      },
      tableList: [],

    };
  },
  components: {
    Crumbs,
    ProvinceCity,
  },
  mounted() {
    this.init();
  },
  activated() {
    if (this.$route.params.customerId) {
      let customerItem = this.tableList.filter((item) => {
        return item.customerId == this.$route.params.customerId;
      });
      let index = this.tableList.indexOf(customerItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  methods: {
    init() {
      this.initDate();
      this.listTable();
      this.getTableHeight();
    },

    formatSex(row, column, cellValue) {
      return cellValue == 1 ? '男' : '女';
    },
    formatTime(row, column, cellValue) {
      return this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    formatStatue(row, column, cellValue) {
      return cellValue == 0 ? '禁用' : '启用';
    },
    initDate() {
      let begin = new Date();
      let nowYear = begin.getFullYear();
      begin.setFullYear(nowYear, 0, 1);
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      // begin.setDate(1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.searchForm.date = [begin, end];
    },
    handleItemChange(val) {
      this.searchForm.provinceCityValues = [val.provinceId, val.cityId, val.areaId];
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        customerCode: this.searchForm.customerCode,
        customerNickName: this.searchForm.customerNickName,
        customerName: this.searchForm.customerName,
        tel: this.searchForm.tel,
        state: this.searchForm.state,
        chooseProvinceId: this.searchForm.provinceCityValues[0],
        chooseCityId: this.searchForm.provinceCityValues[1],
      };
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        (data.createDateBegin = this.$Utils.formatDate(this.searchForm.date[0], 'yyyy-MM-dd hh:mm:ss')),
          (data.createDateEnd = this.$Utils.formatDate(this.searchForm.date[1], 'yyyy-MM-dd hh:mm:ss'));
      }
      this.fetchData(data);
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickDetail(row) {
      this.$router.push({ path: '/user/customerDetail', query: { id: row.customerId } });
    },
    handleClickGetCustomerTel(row) {
      this.$router.push({ path: '/user/customerTelManagement', query: { id: row.customerId, name: row.customerNickName } });
    },
    handleClickGetCustomerDataCall(row) {
      this.$router.push({ path: '/user/customerDataCallManagement', query: { id: row.customerId, name: row.customerNickName } });
    },
    handleClickGetCustomerDataSms(row) {
      this.$router.push({ path: '/user/customerDataSmsManagement', query: { id: row.customerId, name: row.customerNickName } });
    },
    goChat(row) {
      this.$emit('do-chat', row.customerId);
    },
    handleClickResetPass(row) {
      this.$confirm('确定重置该客户登录密码吗？', message.TITLE_PROMPT, {}).then(() => {
        this.$Put(this.$Config.api.customerPass, { customerId: row.customerId })
          .then((res) => {
            this.$notify({
              title: '重置密码成功',
              message: res.data,
              type: 'success',
              duration: 0,
            });
          })
          .catch((error) => {
            if (error.msg) {
              this.$message.error(message.MSG_ACTION_FAIL);
            }
          });
      });
    },
    handleClickDisable(row) {
      let currentState = row.state == 0 ? 1 : 0;
      let txt = row.state == 0 ? '启用' : '禁用';
      this.$confirm('确定' + txt + '该客户吗？', message.TITLE_PROMPT, {}).then(() => {
        let disableFormData = {
          userId: row.customerId,
          loginType: '2',
          state: currentState,
        };
        this.$Put(this.$Config.api.userState, disableFormData)
          .then((res) => {
            row.state = currentState;
            this.$message({
              type: 'success',
              message: message.MSG_ACTION_SUCCESS,
            });
          })
          .catch((error) => {
            if (error.msg) {
              this.$message.error(message.MSG_ACTION_FAIL);
            }
          });
      });
    },
    onSearch() {
      if (this.searchForm.date === null) {
        return this.$message.error(message.MSG_CONFIRM_BEGIN_TIME_IS_NULL);
      }
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.page.pageNo = 1;
      this.initDate();
    },
    fetchData(data) {
      this.$emit('show-loading', true);
      this.$Get(this.$Config.api.customers, data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.page.currentPage = res.data.pageNum;
          this.$emit('show-loading', false);
        })
        .catch((error) => {
          this.$emit('show-loading', false);
          console.error(error);
        });
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.name == '新增客户') {
        vm.init();
      }
    });
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
